WEBAPP['pageClip'] = function() {
	$.each(CLIP.init, function(key, func) {
		func();
	});
};

var CLIP = {
	playerChoice : 0,
	go : function(path) {
		path = '#!' + path;
		if (location.hash == path) {
			$(window).hashchange();
		} else {
			document.location.hash = path;
		}
	}
};

CLIP.init = {
	search : function() {
		$('#searchForm').submit(function() {
			var path = 'Search?' + CLIP.Search.enc($.trim($('#keyword').val()));
			CLIP.go(path);

			// clear
			path = null;

			return false;
		}).find('.del-button').on('click touch', function() {
			$(this).parent().next().val('');
		}).end();
	},

	filters : function() {
		$('#filterForm').find('input:radio').on('change', function() {
			var T = $(this);
			T.closest('.btn-group').find('.label-text').text(T.next().text());

			var vals = [];
			$('#filterForm input:checked').each(function() {
				vals.push($(this).val());
			});
			var path = 'Filters?' + vals.join('|');

			CLIP.go(path);

			// clear
			T = null;
		});
	},

	hash : function() {
		$(window).hashchange(function(e) {
			var hash = location.hash.replace(/^#!/, "");
			var parts = hash.split('?', 2);
			if (CLIP[parts[0]] != undefined) {
				CLIP[parts[0]].go(parts[1]);
			}
		});

		if (location.hash) {
			$(window).hashchange();
		} else {
			$('#filterForm').find('input:radio:checked:first').trigger('change');
		}
	},

	more : function() {
		$('#clips').on('click touch', 'a.clip', function() {
			$('#selClip').removeAttr('id');
			var T = $(this);

			CLIP.Info.currentTitle = T.find('h4').text();
			T.attr('id', 'selClip');

			CLIP.Info.load(T.attr('code'));
			T = null;
			return false;
		});

		$('#clipsMore').on('click touch', function() {
			CLIP.Clips.currentPage++;
			$('#page').val(CLIP.Clips.currentPage);
			CLIP.Clips.more(this);
		});
		$(window).scroll(function(e) {
			if ($('#tabClips').is(':visible')) {
				if ($(window).scrollTop() + 300 * bum.pixelRatio >= $(document).height() - $(window).height()) {
					$('#clipsMore:visible').click()
					// click xong hide liền để tránh trigger liên tục
					.hide();
				}
			}
		});
	},

	info : function() {
		$('#tabInfo').on('click touch', '#chaps a', function() {
			var T = $(this);

			CLIP.Chap.currentTitle = T.text();
			var code = T.addClass('watched').attr('href');
			CLIP.Chap.load(code);

			// clear
			code = null;

			return false;
		});
	},

	tab : function() {
		$('#tabList a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
			if ($(e.target).attr('id') === 'tabClipsButton' && $('#selClip').length > 0) {
				$('body').scrollTo('#selClip');
			} else {
				$('body').scrollTop(0);
			}
		});
	}
};

CLIP.Search = {
	go : function(key) {
		if (key) {
			$('#keyword').val(CLIP.Search.dec(key));
		} else {
			$('#keyword').val('');
		}

		CLIP.Clips.resetPage();
		CLIP.Clips.more();
	},

	// custome
	enc : function(val) {
		return val.replace(/ /g, '+');
	},

	// custome
	dec : function(val) {
		return val.replace(/\+/g, ' ');
	}
};

CLIP.Filters = {
	go : function(data) {
		$('#keyword').val('');

		var parts = data.split('|');
		var sels = $('#filterForm .btn-group');
		for (var i = 0; i < parts.length; i++) {
			$(sels[i]).find('input[value="' + parts[i] + '"]').prop('checked', 'checked');
		}

		CLIP.Clips.resetPage();
		CLIP.Clips.more();
	}
};

CLIP.Clips = {
	// custome
	initPage : 0,
	// custome
	currentPage : 0,
	// custome
	pageSize : 40,

	resetPage : function() {
		CLIP.Clips.currentPage = CLIP.Clips.initPage;
	},

	// custome
	searchUrl : function(keyword) {
		return 'http://m.tv.zing.vn/ajax?f=searchProgram&q=' + encodeURIComponent(keyword) + '&s=date&page=' + CLIP.Clips.currentPage + '&count=40';
	},
	// custome
	filterUrl : function() {
		return 'http://m.tv.zing.vn/ajax?f=genreProgram&count=40&' + $('#filterForm').serialize();
	},

	more : function(item) {
		var url = null;

		var keyword = $('#keyword').val();
		if (keyword) {
			keyword = CLIP.Search.enc(keyword);
			// search
			url = CLIP.Clips.searchUrl(keyword);
		} else {
			// list by filter
			url = CLIP.Clips.filterUrl();
		}

		bum.api.fetchUrl(url, CLIP.Clips.headers || CLIP.Chap.headers, CLIP.Clips.getMore);

		if (CLIP.Clips.currentPage === 0) {
			$('#clips').empty();
		}
		$('#tabClipsButton').tab('show');

		// clear
		url = keyword = null;
	},

	moreCount : 0,
	getMore : function(text) {
		if (text == null) {
			bum.api.showToast('Nội dung không tìm thấy hoặc đã hết...');
			return;
		}

		CLIP.Clips.moreCount = 0;

		var html = CLIP.Clips.moreHtml(text);

		if (html.length == 0) {
			bum.api.showToast('Nội dung không tìm thấy hoặc đã hết...');
			return;
		}

		html = html.join('');

		// trang đầu thì đè, trang next thì append
		if (CLIP.Clips.currentPage == CLIP.Clips.initPage) {
			$('#clips').html(html);
		} else {
			$('#clips').append(html);
		}

		// ẩn hiện nút load more
		if (CLIP.Clips.moreCount >= CLIP.Clips.pageSize) {
			$('#clipsMore').show();
		} else {
			$('#clipsMore').hide();
		}

		// clear
		CLIP.Clips.moreCount = html = null;
	},

	// custome
	moreHtml : function(text) {
		var html = [];
		$.each(text.split('<a class="content-items"'), function(i, clip) {
			if (i > 0) {
				++CLIP.Clips.moreCount;
				var code = bum.util.parse(clip, 'href="/p/', '">');
				var title = bum.util.parse(clip, '<h3>', '</h3>');
				var img = bum.util.parse(clip, 'src="', '"');

				html.push('<a class="item clip" href="#" code="', code, '"><div class="cw">');
				html.push('<img src="http://cdn.bum.vn/_.gif" style="background-image:url(', img, ');"/>');
				html.push('<div class="iw"><h4>', title, '</h4>');
				html.push('<h5></h5></div>');
				html.push('</div></a>');
			}
		});
		return html;
	}
};

CLIP.Info = {
	code : null,
	currentTitle : null,

	genInfoCacheKey : function(code) {
		return 'vtube.info.' + code;
	},

	// custome
	infoUrl : function(code) {
		return 'http://m.tv.zing.vn/p/' + code;
	},

	load : function(code) {
		// focus tab
		$('#tabInfo').empty();
		$('#tabInfoButton').tab('show');

		CLIP.Info.code = code;

		bum.api.fetchUrl(CLIP.Info.infoUrl(code), CLIP.Chap.headers, CLIP.Info.getInfo);
	},

	// custome
	parseInfo : function(text) {
		text = bum.util.parse(text, '<!--End .top-head -->', '<!--End .sugguest-->');
		if (text == null) {
			return null;
		}

		var poster = bum.util.parse(text, '<img src="', '"');
		var title = bum.util.parse(text, '<h3>', '</h3>');
		var originalTitle = bum.util.parse(text, '<h4>', '</h4>');
		var intro = bum.util.parse(text, '<p id="description" class="rows2" expand="rows2">', '</p>');

		var clip = {
			poster : poster,
			title : title,
			originalTitle : originalTitle,
			intro : intro
		};

		var url = bum.util.parse(text, 'autoload-src="', '"></div>');
		if (url) {
			bum.api.fetchUrl(url + '&page=1&count=200', CLIP.Chap.headers, CLIP.Info.getSuggests);
		}

		return clip;
	},

	// zing only
	getSuggests : function(html) {
		$.each(html.split('<a href="/series/'), function(i, part) {
			if (i > 0) {
				var code = bum.util.parse(part, '/', '.html');
				var url = 'http://m.tv.zing.vn/ajax?f=loadMediaSeries&page=1&count=500&id=' + code;

				bum.api.fetchUrl(url, CLIP.Chap.headers, CLIP.Info.getChaps);
			}
		});
	},

	// zing only
	getChaps : function(text) {
		var html = [];
		text = text.replace(/Tập /gi, '');
		$.each(text.split('<a class="content-items" href="/video/'), function(i, part) {
			if (i > 0) {
				var code = bum.util.parse(part, '/', '.html');
				var name = bum.util.parse(part, '<h3>', '</h3>');

				html.push('<a href="' + code + '">' + name + '</a>');
			}
		});

		$('#chaps').append('<div>' + html.reverse().join('') + '</div>');
	},

	getInfo : function(text) {
		CLIP.Info.renderInfo(CLIP.Info.parseInfo(text));

		// clear
		poster = title = detail = intro = clip = null;
	},

	renderInfo : function(clip) {
		if (!clip) {
			return;
		}

		var html = [];

		html.push('<div class="clearfix film-basic"><img class="thumb" align="left" src="', clip.poster, '"/>');
		html.push('<h4>', clip.title, '</h4>');
		if (clip.originalTitle) {
			html.push('<h5>', clip.originalTitle, '</h5>');
		}
		if (clip.detail) {
			html.push(clip.detail);
		}
		html.push('</div>');

		html.push('<div class="nav">Số tập</div>');
		html.push('<div class="chaps" id="chaps">');
		if (clip.chaps) {
			for (var i = 0; i < clip.chaps.length; i++) {
				html.push(clip.chaps[i]);
			}
		} else if (CLIP.Chap.chaps != null) {
			html.push(CLIP.Chap.chaps);
			CLIP.Chap.chaps = null;
		}
		html.push('</div>');
		html.push('<div class="nav">Giới thiệu</div>');
		html.push('<div class="intro"><div class="inw">', clip.intro, '</div></div>');

		$('#tabInfo').html(html.join(''));

		// clear
		html = null;
	}
};

CLIP.Chap = {
	// custome
	headers : [ 'Accept', 'text/plain, text/html', 'Host', 'm.tv.zing.vn', 'Cache-Control', 'max-age=0', 'Connection', 'close', 'User-Agent',
			'Mozilla/5.0 (Linux; U; Android 2.2; en-us; DROID2 GLOBAL Build/S273) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1' ].join('|'),

	// custome
	chapUrl : function(code) {
		return 'http://m.tv.zing.vn/video/a/' + code + '.html';
	},
	// custome
	streamUrl : function(text) {
		return bum.util.parse(text, '<source src="', '"');
	},

	load : function(code) {
		bum.api.fetchUrl(CLIP.Chap.chapUrl(code), CLIP.Chap.headers, CLIP.Chap.getChap);
	},
	getChap : function(text) {
		var url = CLIP.Chap.streamUrl(text);

		if (url && url.indexOf('http') === 0) {
			CLIP.Chap.playStream(url);
		} else {
			bum.api.showToast('Nội dung không tìm thấy');
		}
	},

	currentTitle : null,
	currentUid : null,
	playStream : function(url) {
		bum.api.playVideoUrl(url, CLIP.Info.currentTitle + ' ' + CLIP.Chap.currentTitle, CLIP.Chap.currentUid || '');
	}
};